<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>绘制一个点</title>
  </head>
  <body>
    <!--canvas标签创建一个宽高均为500像素，背景为蓝色的矩形画布-->
    <canvas id="webgl" width="500" height="500" style="background-color: blue"></canvas>
    <script>
      // 1.获取webgl对象
      var canvas = document.getElementById('webgl')
      var gl = canvas.getContext('webgl')
      // 2.设置顶点着色器和片元着色器
      var vsSource = `void main(){
    gl_Position =vec4(0.0,0.0,0.0,1.0);
    gl_PointSize=20.0;
      }`
      var fsSource = `void main(){
       gl_FragColor = vec4(1.0,2.0,0.0,3.0);

}`
      // 3.初始化编辑器
      // initShader函数实现
      function initShader(gl, vsSource, fsSource) {
        function compileShader(type, source) {
          const shader = gl.createShader(type)
          gl.shaderSource(shader, source)
          gl.compileShader(shader)
          if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
            console.error('An error occurred compiling the shaders:', gl.getShaderInfoLog(shader))
            gl.deleteShader(shader)
            return null
          }
          return shader
        }

        const vertexShader = compileShader(gl.VERTEX_SHADER, vsSource)
        const fragmentShader = compileShader(gl.FRAGMENT_SHADER, fsSource)
        const shaderProgram = gl.createProgram()
        gl.attachShader(shaderProgram, vertexShader)
        gl.attachShader(shaderProgram, fragmentShader)
        gl.linkProgram(shaderProgram)

        if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
          console.error('Unable to initialize the shader program:', gl.getProgramInfoLog(shaderProgram))
          return null
        }

        return shaderProgram
      }

      const program = initShader(gl, vsSource, fsSource)
      gl.useProgram(program)
      //   4.绘制一个点
      gl.drawArrays(gl.POINTS, 0, 1)
    </script>
  </body>
</html>
